let app = getApp();
import {
  getIndexList,
  getCategoryTitle,
  getIndexRecomList,
  extensionStatistics
} from "../../api";
import {
  baseImgUrl,
  programTitle
} from "../../setting";
const utils = require('../../utils/validate');
Page({
  data: {
    baseurl_img: baseImgUrl,
    allInfo: [],
    fixedTop: false,
    topCity: '全国',
    advertiseList: [],
    indexPage: 1,
    pageSize: 8,
    indexTotal: 0,
    scrollList: [],
    selectCateId: 0,
    recomPage: 1,
    recommendList: [],
    recommendTotal: 0,
    canReachBottom: true,
    labelList: [],
    systemInfo: {},
    show: false,
    allFlag: false,
    isIos: ""
  },
  onLoad(query) {

    if (query) {
      let queryData = JSON.parse(JSON.stringify(query))
      if (queryData.saleuserid && queryData.saleuserid != 'undefined' && queryData.saleuserid != 'null') {
        app.globalData.orderFrom = queryData.from || ''
        app.globalData.jumpData = queryData
        app.globalData.sale_user_id = queryData.saleuserid
      }

      console.log(query);
      console.log(app.globalData);
      if (app.globalData.sale_user_id) {
        extensionStatistics({
          sale_user_id: app.globalData.sale_user_id,
        }).then(res1 => {})
      }
    }

    // 页面加载
    this.getData();
    this.getRecomList();
    this.getCateTitle()
    my.getSystemInfo({
      success: (res) => {
        this.setData({
          systemInfo: res
        })
      }
    })

    my.setNavigationBar({
      title: programTitle, // 设置导航栏标题
      backgroundColor: '#FFFFFF', // 设置背景颜色（比如红色）
      frontColor: '#000000' // 设置前景颜色（比如白色文本）
    });
  },
  onReady() {
    my.setNavigationBar({
      title: programTitle, // 设置导航栏标题
      backgroundColor: '#FFFFFF', // 设置背景颜色（比如红色）
      frontColor: '#000000' // 设置前景颜色（比如白色文本）
    });
  },
  onShow() {
    // 获取系统信息
    const systemInfo = my.getSystemInfoSync(); // 获取设备信息，返回一个对象
    console.log("设备型号: ", systemInfo.platform === "iOS");

    systemInfo.platform === "iOS" ? this.setData({
      isIos: "90rpx"
    }) : this.setData({
      isIos: "90rpx"
    })


    // // 获取安全区域（包含顶部和底部安全区域）
    // const safeArea = systemInfo.safeArea;
    // // 获取顶部安全区域的距离
    // const safeTop = safeArea.top;
    // console.log("顶部安全区域距离: ", safeTop);
    setTimeout(() => {
      my.hideLoading()
    }, 1000);
    let index = my.getStorageSync({
      key: 'index_page'
    }).data;
    console.log(index);
    if (!index) {
      my.setStorageSync({
        key: 'index_page',
        data: '1'
      });
      this.setData({
        show: true
      });
    }



  },

  getData(flag) {
    const {
      indexPage,
      allInfo
    } = this.data
    getIndexList({
      page: flag ? indexPage + 1 : 1,
    }).then(res => {
      my.stopPullDownRefresh()
      let indexData = res.data
      indexData.forEach(item => {
        item.params = JSON.parse(item.params)
      })
      let list = [...allInfo]
      if (flag) {
        list = [...list, ...indexData]
      } else {
        list = [...indexData]
      }

      this.setData({
        allFlag: list.some(item => item.type === 1),
        allInfo: list,
        indexPage: res.current_page,
        indexTotal: res.total
      })
    }).catch(err => {
      my.stopPullDownRefresh();
    })
  },
  onPageScroll(e) {
    const that = this;
    // console.log(e.scrollTop);
    if (e.scrollTop > 200) {
      that.setData({
        fixedTop: true
      })
    } else {
      that.setData({
        fixedTop: false
      })
    }
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: programTitle,
      desc: '信用免押一站式租赁服务平台',
      path: 'pages/index/index',
    };
  },
  onClickJump(e) {

    const {
      jumpType,
      jumpUrl
    } = e.info
    if (jumpType == 1) {
      if (jumpUrl.indexOf('plugin') > -1) {
        my.navigateTo({
          url: jumpUrl
        });
      } else {
        my.navigateTo({
          url: '../../' + jumpUrl
        })
      }
      // my.navigateTo({ url: '../webView/webView?jumpUrl=' + jumpUrl + '&jumpType=' + jumpType })
    } else if (jumpType == 2) {
      my.navigateTo({
        url: '../../pagesA/pages/productDetails/productDetails?goodsId=' + e.info.goods.goods_id + '&sale_user_id=' + app.globalData.sale_user_id
      })
    }
  },
  onJumpDetails(e) {
    let id
    if (e.info && e.info.goods_id) {
      id = e.info.goods_id
    } else {
      id = e.currentTarget.dataset.goods_id || e.currentTarget.dataset.info.goods_id
    }
    if (id) {
      my.navigateTo({
        url: '../../pagesA/pages/productDetails/productDetails?goodsId=' + id + '&sale_user_id=' + app.globalData.sale_user_id
      })
    }
  },
  jumpHuBei() {},
  getCateTitle() {
    getCategoryTitle().then(res => {
      if (res.length) {
        console.log(res);
        this.setData({
          scrollList: res,
          selectCateId: this.data.selectCateId ? this.data.selectCateId : res[0].id,
        })
        this.getRecomList();
      }
    })
  },
  getRecomList(flag) {
    const {
      selectCateId,
      recomPage,
      recommendList
    } = this.data
    getIndexRecomList({
      cateId: selectCateId,
      page: flag ? recomPage + 1 : 1,
    }).then(res => {
      my.stopPullDownRefresh();
      if (res.data.length > 0) {
        let list = [...recommendList]
        if (flag) {
          list = [...list, ...res.data];
        } else {
          list = res.data;
        }
        list.forEach(item => {
          if (item.rent_label) {
            const arr = item.rent_label.replace(/,/g, '，').split('，').filter((p, idx) => p != '' && idx < 2);
            item['labelList'] = arr
          }
        })
        this.setData({
          recommendList: list,
          recommendTotal: res.total,
          recomPage: res.current_page,
        })
      }
    }).catch(err => {
      my.stopPullDownRefresh();
    })
  },
  seleteScroll(e) {
    let id = e.currentTarget.dataset.id
    if (id) {
      this.setData({
        selectCateId: id,
        recommendList: [],
      })
      this.getRecomList()
    }
  },
  selectCity() {
    const that = this
    my.chooseCity({
      showHotCities: true,
      setLocatedCity: true,
      success: (res) => {
        that.setData({
          topCity: res.city
        })
      },
    });
    // my.getLocation({
    //   type: 1,
    //   success(res) {
    //     that.setData({
    //       topCity: res.city.slice(0, 2)
    //     })
    //     my.chooseCity({
    //       showHotCities: true,
    //       setLocatedCity: true,
    //       success: (res) => {
    //         that.setData({
    //           topCity: res.city
    //         })
    //       },
    //     });
    //   },
    //   fail(res){
    //     my.chooseCity({
    //       showHotCities: true,
    //       setLocatedCity: true,
    //       success: (res) => {

    //       },
    //     });
    //   },
    // });

  },
  searchTo() {
    my.navigateTo({
      url: '../../pagesA/pages/search/search'
    })
  },
  toItemClassify(e) {

    let url = e.currentTarget.dataset.jumpUrl
    if(!url) return
    const res = utils.parseAlipayScheme(url)
    my.navigateToMiniProgram({
      appId: res.appId,
      path: res.path,
      success: (res) => {
       
      },
      fail: (res) => {
     
      }
    });
   
  },
  hotRent(e) {
    let url = e.currentTarget.dataset.jumpUrl
    if (url) {
      my.navigateTo({
        url: '../../' + url
      })
    }
  },
  payToRent(e) {
    let url = e.currentTarget.dataset.jumpUrl
    if (url) {
      my.navigateTo({
        url: '../../' + url
      })
    }
  },
  // 使用 scheme 跳转小程序
  navigateToMiniProgramScheme(scheme) {
    var params = this.schemeToParams(scheme);

    if (params) {
      my.navigateToMiniProgram({
        ...params
      });
    } else {}
  },

  // 将 scheme 转换为 my.navigateToMiniProgram 的参数
  schemeToParams(scheme) {
    if (!scheme.includes('alipays:')) {
      return {
        message: '! 非 alipays: 开头'
      };
    }
    var params = {};
    var parseQuery = (str) => {
      return str.replace(/^.*?\?/, '').split('&').map(s => {
        var p = s.includes('=') ? s.indexOf('=') : s.length;
        return [s.slice(0, p), s.slice(p + 1)].map(decodeURIComponent);
      });
    };
    for (var [k, v] of parseQuery(scheme)) {
      if (k == 'appId') {
        if (v.length != 16) {
          return {
            message: `! 非 16 位 appId '${v}'`
          };
        }
      } else if (k == 'page') {
        k = 'path';
      } else if (k == 'query') {
        var o = {};
        for (var [x, y] of parseQuery(v)) {
          o[x] = y;
        }
        v = o;
      } else {
        return {
          message: `! 不支持参数 '${k}' `
        };
      }
      params[k] = v;
    }
    return params;
  },



  brandClick(e, jumpType) {
    if (jumpType == 1) {
      this.navigateToMiniProgramScheme(
        e
      );
    } else if (jumpType == 2) {
      my.navigateTo({
        url: '../../pagesA/pages/productDetails/productDetails?goodsId=' + e + '&sale_user_id=' + app.globalData.sale_user_id
      })
    }
  },
  onReachBottom() {
    const {
      allInfo,
      indexTotal,
      scrollList,
      recommendList,
      recommendTotal
    } = this.data
    // if (!scrollList.length) {
    //   this.getCateTitle()
    // }
    if (allInfo.length < indexTotal) {
      this.getData(true);
    }
    if (recommendList.length && recommendList.length < recommendTotal) {
      this.getRecomList(true)
    }
  },
  onPullDownRefresh() {
    this.getData()
  },
});